import { getUserInfo, logout } from '@/apis/system/user';
import { defineStore } from 'pinia';
import { useRouter } from 'vue-router';

export const useUserStore = defineStore('userStore', {
  state: () => ({
    userInfo: null,
    token: '',
    roles: [],
    permissions: [],
  }),
  getters: {},
  actions: {
    setToken(token: string) {
      this.token = token;
      localStorage.setItem('token', token);
    },

    getToken(): string {
      return this.token || localStorage.getItem('token') || '';
    },

    async logout() {
      const router = useRouter();
      this.$reset();
      localStorage.removeItem('token');
      await logout();
      router.push('/login');
    },

    async fetchUserInfo() {
      const res: any = await getUserInfo();
      if (res.code === 200) {
        this.userInfo = res.data;
        this.permissions = res.data.permissions;
        this.roles = res.data.roles;
        return this.userInfo;
      }
    },
  },
});
